/**
 * Model 模型
 */
function Model() {
  var val = 0;
  // 增加数据
  this.add = function(v) {
    if (val < 100) {
      val += v;
    }
  };
  // 减少数据
  this.sub = function(v) {
    if (val > 0) {
      val -= v;
    }
  };
  // 获取数据
  this.getVal = function() {
    return val;
  };
  /**
   * 观察者模式
   */
  var self = this,
      views = [];

  this.register = function(view) {
    views.push(view);
  };

  this.notify = function() {
    for(var i = 0; i < views.length; i++) {
      views[i].render(self);
    }
  };
};

/**
 * View 视图
 */
function View(controller) {
  var $calculator = $('#calculator');
  var $num = $calculator.find('.num');
  var $addBtn = $calculator.find('.js-add');
  var $subBtn = $calculator.find('.js-sub');

  this.render = function(model) {
    $num.text(model.getVal() + '元');
  };

  /* 绑定事件 */
  $addBtn.click(controller.increase);
  $subBtn.click(controller.decrease);
};

/**
 * Controller 控制器
 */
function Controller() {
  var model = null,
  view = null;

  this.init = function() {
    /* 初始化Model和View */
    model = new Model();
    view = new View(this);

    // View 观察注册 Model，当Model更新就会去通知View啦
    model.register(view);
    model.notify();
  };

  // 让Model更新数值并通知View更新视图 
  this.increase = function() {
    model.add(1);
    model.notify();
  };
  this.decrease = function() {
    model.sub(1);
    model.notify();
  };
};

var controller = new Controller();
controller.init();